using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Serilog;

// WPF 相关（使用别名）
using WPF = System.Windows;

namespace PC
{
    public partial class RegisterWindow : WPF.Window
    {
        private readonly ILogger _logger;
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://localhost:3003";

        public RegisterWindow()
        {
            InitializeComponent();
            _logger = Log.Logger;
            _httpClient = new HttpClient();
        }

        private async void RegisterButton_Click(object sender, WPF.RoutedEventArgs e)
        {
            try
            {
                var username = UsernameTextBox.Text.Trim();
                var password = PasswordBox.Password.Trim();
                var confirmPassword = ConfirmPasswordBox.Password.Trim();

                if (string.IsNullOrEmpty(username))
                {
                    WPF.MessageBox.Show("请输入用户名", "错误", WPF.MessageBoxButton.OK, WPF.MessageBoxImage.Error);
                    return;
                }

                if (string.IsNullOrEmpty(password))
                {
                    WPF.MessageBox.Show("请输入密码", "错误", WPF.MessageBoxButton.OK, WPF.MessageBoxImage.Error);
                    return;
                }

                if (password != confirmPassword)
                {
                    WPF.MessageBox.Show("两次输入的密码不一致", "错误", WPF.MessageBoxButton.OK, WPF.MessageBoxImage.Error);
                    return;
                }

                var data = new { username, password };
                var content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync($"{_baseUrl}/register", content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    WPF.MessageBox.Show("注册成功！", "提示", WPF.MessageBoxButton.OK, WPF.MessageBoxImage.Information);
                    DialogResult = true;
                    Close();
                }
                else
                {
                    var error = JsonSerializer.Deserialize<ErrorResponse>(responseContent);
                    WPF.MessageBox.Show(error?.Message ?? "注册失败", "错误", WPF.MessageBoxButton.OK, WPF.MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "注册失败");
                WPF.MessageBox.Show("注册失败：" + ex.Message, "错误", WPF.MessageBoxButton.OK, WPF.MessageBoxImage.Error);
            }
        }

        private void CancelButton_Click(object sender, WPF.RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private class ErrorResponse
        {
            public string Message { get; set; } = string.Empty;
        }
    }
} 